<!--
 * @Description: 流程代码预览
 * @Author: DHL
 * @Date: 2022-04-20 16:36:27
 * @LastEditors: DHL
 * @LastEditTime: 2022-11-03 10:16:50
-->
<template>
  <tw-dialog
    v-model="visible"
    title="预览"
    width="1100px"
    height="620px"
    :scrollbar="false"
    customClass="process-preview-wrapper"
    @close="handleClose"
    @zoom="handleZoom"
  >
    <div class="monaco-wrapper">
      <div ref="codeMonacoRef" class="tw-code-monaco"></div>
    </div>
  </tw-dialog>
</template>

<script lang="ts">
  export default { name: 'ProcessPreview' }
</script>

<script setup lang="ts">
  import { nextTick, ref } from 'vue'
  import * as monaco from 'monaco-editor'

  /**
   * 显示弹框
   */
  const visible = ref(false)

  const codeMonacoRef = ref()

  const language = ref('')
  const value = ref('')

  let codeMonaco: monaco.editor.IStandaloneCodeEditor | null = null

  /**
   * 打开弹框
   */
  function handleOpen(type: string, code: string) {
    visible.value = true

    language.value = type
    value.value = code

    initMonaco()
  }

  /**
   * 关闭弹框
   */
  function handleClose() {
    if (codeMonaco) {
      codeMonaco.dispose()
    }
    visible.value = false
  }

  /**
   * 窗口缩放时会触发该事件
   */
  function handleZoom() {
    nextTick(() => {
      initMonaco()
    })
  }

  /**
   * 初始化monaco组件
   */
  function initMonaco() {
    const options = {
      value: value.value,
      language: language.value,
      theme: 'vs-dark'
    }

    if (codeMonaco) {
      codeMonaco.dispose()
    }

    nextTick(() => {
      codeMonaco = monaco.editor.create(codeMonacoRef.value, options)
    })
  }

  defineExpose({ handleOpen })
</script>

<style lang="scss">
  .process-preview-wrapper {
    .monaco-wrapper {
      width: 100%;
      height: 100%;
      padding: 10px;

      .tw-code-monaco {
        width: calc(100% - 20px);
        height: calc(100% - 20px);
        min-height: 600px;
      }
    }

    &.is-fullscreen {
      .monaco-wrapper {
        width: calc(100% - 20px);
        height: calc(100% - 20px);

        .tw-code-monaco {
          width: 100%;
          height: 100%;
          min-height: 600px;
        }
      }
    }
  }
</style>
